package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.api.AuthInterceptor;
import com.example.myapplication.api.PasswordApi;
import com.example.myapplication.model.Password;
import com.example.myapplication.adapter.PasswordAdapter;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class PasswordListActivity extends AppCompatActivity {
    private PasswordApi passwordApi;
    private PasswordAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_password_list);

        // 设置Toolbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        // 初始化Retrofit，添加token拦截器
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new AuthInterceptor(this))
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://10.0.2.2:8080/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        
        passwordApi = retrofit.create(PasswordApi.class);

        // 初始化RecyclerView和适配器
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new PasswordAdapter();
        recyclerView.setAdapter(adapter);

        // 加载密码列表
        refreshPasswordList();

        // 设置添加按钮点击事件
        FloatingActionButton fabAdd = findViewById(R.id.fabAdd);
        fabAdd.setOnClickListener(v -> {
            Intent intent = new Intent(this, AddPasswordActivity.class);
            startActivity(intent);
        });

        // 在onCreate方法中设置点击监听
        adapter.setOnPasswordClickListener(password -> {
            Intent intent = new Intent(this, PasswordDetailActivity.class);
            intent.putExtra("password", password);
            startActivity(intent);
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 每次返回到这个页面时刷新列表
        refreshPasswordList();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_password_list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            // 返回登录界面
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
            return true;
        } else if (itemId == R.id.action_refresh) {
            refreshPasswordList();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void refreshPasswordList() {
        passwordApi.getPasswords().enqueue(new Callback<List<Password>>() {
            @Override
            public void onResponse(Call<List<Password>> call, Response<List<Password>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    adapter.setPasswords(response.body());
                    adapter.notifyDataSetChanged();
                } else {
                    if (response.code() == 401) {
                        // token失效，返回登录界面
                        Toast.makeText(PasswordListActivity.this, 
                            "登录已过期，请重新登录", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(PasswordListActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        Toast.makeText(PasswordListActivity.this, 
                            "获取密码列表失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<List<Password>> call, Throwable t) {
                Toast.makeText(PasswordListActivity.this, 
                    "网络错误，请检查网络连接", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onBackPressed() {
        // 显示退出确认对话框
        new AlertDialog.Builder(this)
            .setTitle("退出应用")
            .setMessage("确定要退出应用吗？")
            .setPositiveButton("确定", (dialog, which) -> {
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();
            })
            .setNegativeButton("取消", null)
            .show();
    }
} 